package cn.smxy.search.listener;

import cn.smxy.client.PlantClient;
import cn.smxy.doc.PlantDoc;
import cn.smxy.pojo.Plant;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ApplicationRunListener implements ApplicationRunner {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private PlantClient plantClient;

    private String createIndex = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"plantId\": {\n" +
            "        \"type\": \"long\"\n" +
            "      },\n" +
            "      \"plantName\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"plantSpecific\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"latinName\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"categoryId\": {\n" +
            "        \"type\": \"long\"\n" +
            "      },\n" +
            "      \"familyId\": {\n" +
            "        \"type\": \"long\"\n" +
            "      },\n" +
            "      \"plantDescription\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": true\n" +
            "      },\n" +
            "      \"plantPicture\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"userId\": {\n" +
            "        \"type\": \"long\" \n" +
            "      },\n" +
            "      \"createTime\": {\n" +
            "        \"type\": \"long\"\n" +
            "      },\n" +
            "      \"isChoiceness\": {\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"all\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}\n";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 数据库数据初始化
        // 查询全部数据
        List<Plant> list = plantClient.list();

        // 判断是否存在plant索引
        GetIndexRequest getIndexRequest = new GetIndexRequest("plant");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (!exists) {
            // 不存在，创建新索引
            CreateIndexRequest createIndexRequest = new CreateIndexRequest("product");
            createIndexRequest.source(createIndex, XContentType.JSON);
            client.indices().create(createIndexRequest,RequestOptions.DEFAULT);
        }

        // 删除全部数据
        DeleteByQueryRequest delete = new DeleteByQueryRequest("plant");
        delete.setQuery(QueryBuilders.matchAllQuery());
        client.deleteByQuery(delete,RequestOptions.DEFAULT);

        // 插入全部数据
        BulkRequest bulkRequest = new BulkRequest();
        ObjectMapper objectMapper = new ObjectMapper();
        for (Plant plant : list) {
            PlantDoc plantDoc = new PlantDoc(plant);
            bulkRequest.add(new IndexRequest("plant")
                    .id(plantDoc.getPlantId().toString())
                    .source(objectMapper.writeValueAsString(plantDoc),XContentType.JSON));
        }

        client.bulk(bulkRequest,RequestOptions.DEFAULT);
        log.info("ApplicationRunListener.run业务结束，结果为:{}","完成数据更新");
    }
}
